package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 获取当前登录用户的信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        // 验证码校验
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode,captcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 验证码一致需要进行删除
        redisTemplate.delete("user:validate" + key);
        // 需要查询的是 sys_user 的表中的数据
        // 数据库中的密码用来 md5 加密
        // token 就是一个唯一的字符串，所以UUID
        // 需要将 token 放置 redis 中，以便后续验证
        String userName = loginDto.getUserName();
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (sysUser == null){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        String input_password =
                DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        String dateBase_password = sysUser.getPassword();
        if (!input_password.equals(dateBase_password)){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 生成一个唯一的 token
        String token = UUID.randomUUID().toString().replace("-", "");
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        //return new LoginVo().setToken(token);
        // 放置 redis
        redisTemplate.opsForValue()
                .set("user:login"+token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);

        //System.out.println("token:"+token+"///////////////////////////////////////////////////////////////");
        return loginVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum , pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto) ;
        PageInfo pageInfo = new PageInfo(sysUserList) ;
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        // 用户名不能重复
        // 输入的密码进行加密
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        // 设置 status 值 1 表示可用 0 表示不可用
        sysUser.setStatus(1);
        sysUserMapper.save(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    @Log(title = "用户分配角色", businessType = 0)
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 根据 userId 删除之前分配过的数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        // 重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for(Long roleId : roleIdList){
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(), roleId);
        }
    }


}
